<template>
  <div class="role-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="text-title">角色管理</h1>
      <p class="text-caption">管理系统角色和权限分配</p>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-bar">
        <input 
          v-model="searchQuery"
          class="apple-input"
          placeholder="搜索角色名称或描述..."
          @input="handleSearch"
        >
      </div>
      <button 
        class="apple-button apple-button--primary"
        @click="showCreateDialog = true"
      >
        新建角色
      </button>
    </div>

    <!-- 角色列表 -->
    <div class="roles-container">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p class="text-body">加载中...</p>
      </div>

      <div v-else-if="roles.length === 0" class="empty-state">
        <div class="empty-icon">👥</div>
        <h3 class="text-subheading">暂无角色</h3>
        <p class="text-caption">点击"新建角色"开始创建第一个角色</p>
      </div>

      <div v-else class="roles-grid">
        <div 
          v-for="role in roles" 
          :key="role.id"
          class="apple-card role-card"
          @click="handleRoleClick(role)"
        >
          <div class="apple-card__header">
            <div class="role-header">
              <div class="role-info">
                <h3 class="text-subheading">{{ role.name }}</h3>
                <p class="text-caption role-code">{{ role.code }}</p>
              </div>
              <div class="role-status">
                <span 
                  :class="['apple-tag', role.is_active ? 'apple-tag--success' : 'apple-tag--danger']"
                >
                  {{ role.is_active ? '激活' : '禁用' }}
                </span>
                <span 
                  v-if="role.is_system"
                  class="apple-tag apple-tag--warning"
                >
                  系统角色
                </span>
              </div>
            </div>
          </div>

          <div class="apple-card__body">
            <p class="text-body role-description">
              {{ role.description || '暂无描述' }}
            </p>
            
            <div class="role-stats">
              <div class="stat-item">
                <span class="stat-label">用户数量</span>
                <span class="stat-value">{{ role.user_count || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">权限级别</span>
                <span class="stat-value">L{{ role.level || 0 }}</span>
              </div>
            </div>
          </div>

          <div class="apple-card__footer">
            <button 
              class="apple-button apple-button--text"
              @click.stop="editRole(role)"
              :disabled="role.is_system"
            >
              编辑
            </button>
            <button 
              class="apple-button apple-button--text"
              @click.stop="managePermissions(role)"
            >
              权限管理
            </button>
            <button 
              class="apple-button apple-button--text apple-button--danger"
              @click.stop="deleteRole(role)"
              :disabled="role.is_system"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1" class="pagination">
      <button 
        class="apple-button apple-button--secondary"
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      
      <div class="page-numbers">
        <button
          v-for="page in visiblePages"
          :key="page"
          :class="['apple-button', currentPage === page ? 'apple-button--primary' : 'apple-button--secondary']"
          @click="changePage(page)"
        >
          {{ page }}
        </button>
      </div>
      
      <button 
        class="apple-button apple-button--secondary"
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 创建角色对话框 -->
    <RoleCreateDialog
      v-model="showCreateDialog"
      @created="handleRoleCreated"
    />

    <!-- 编辑角色对话框 -->
    <RoleEditDialog
      v-model="showEditDialog"
      :role="selectedRole"
      @updated="handleRoleUpdated"
    />

    <!-- 权限管理对话框 -->
    <PermissionManageDialog
      v-model="showPermissionDialog"
      :role="selectedRole"
      @updated="handlePermissionsUpdated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RoleCreateDialog from './components/RoleCreateDialog.vue'
import RoleEditDialog from './components/RoleEditDialog.vue'
import PermissionManageDialog from './components/PermissionManageDialog.vue'
import { roleApi } from '@/api/rbac'
import type { Role } from '@/types/rbac'

// 响应式数据
const roles = ref<Role[]>([])
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 对话框状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showPermissionDialog = ref(false)
const selectedRole = ref<Role | null>(null)

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 加载角色列表
const loadRoles = async () => {
  loading.value = true
  try {
    const response = await roleApi.getRoles({
      page: currentPage.value,
      size: pageSize.value,
      search: searchQuery.value || undefined
    })
    
    if (response.success) {
      roles.value = response.data
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadRoles()
}

// 换页
const changePage = (page: number) => {
  currentPage.value = page
  loadRoles()
}

// 角色点击
const handleRoleClick = (role: Role) => {
  selectedRole.value = role
  // 可以添加角色详情查看逻辑
}

// 编辑角色
const editRole = (role: Role) => {
  selectedRole.value = role
  showEditDialog.value = true
}

// 管理权限
const managePermissions = (role: Role) => {
  selectedRole.value = role
  showPermissionDialog.value = true
}

// 删除角色
const deleteRole = async (role: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${role.name}"吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'apple-button--danger'
      }
    )
    
    // TODO: 调用删除API
    ElMessage.success('角色删除成功')
    loadRoles()
  } catch {
    // 用户取消
  }
}

// 事件处理
const handleRoleCreated = () => {
  loadRoles()
  ElMessage.success('角色创建成功')
}

const handleRoleUpdated = () => {
  loadRoles()
  ElMessage.success('角色更新成功')
}

const handlePermissionsUpdated = () => {
  loadRoles()
  ElMessage.success('权限配置已更新')
}

// 监听搜索变化
watch(searchQuery, () => {
  if (!searchQuery.value) {
    handleSearch()
  }
})

// 组件挂载
onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.role-management {
  padding: var(--spacing-lg);
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: var(--spacing-xl);
  text-align: center;
}

.page-header .text-caption {
  margin-top: var(--spacing-sm);
  color: var(--text-secondary);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  gap: var(--spacing-md);
}

.search-bar {
  flex: 1;
  max-width: 400px;
}

.roles-container {
  min-height: 400px;
}

.loading-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--apple-gray-5);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--spacing-md);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 64px;
  margin-bottom: var(--spacing-md);
  opacity: 0.5;
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: var(--spacing-lg);
}

.role-card {
  cursor: pointer;
  transition: all var(--duration-normal) var(--ease-out);
}

.role-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-large);
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.role-info .text-subheading {
  margin-bottom: var(--spacing-xs);
}

.role-code {
  font-family: 'SF Mono', Monaco, monospace;
  background: var(--bg-tertiary);
  padding: 2px 6px;
  border-radius: var(--radius-small);
}

.role-status {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  align-items: flex-end;
}

.role-description {
  margin-bottom: var(--spacing-md);
  line-height: 1.6;
  min-height: 44px;
}

.role-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-secondary);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-label {
  font-size: 11px;
  color: var(--text-tertiary);
  margin-bottom: var(--spacing-xs);
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-primary);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: var(--spacing-xl);
  gap: var(--spacing-sm);
}

.page-numbers {
  display: flex;
  gap: var(--spacing-xs);
}

@media (max-width: 768px) {
  .role-management {
    padding: var(--spacing-md);
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar {
    max-width: none;
    margin-bottom: var(--spacing-md);
  }
  
  .roles-grid {
    grid-template-columns: 1fr;
    gap: var(--spacing-md);
  }
  
  .role-header {
    flex-direction: column;
    gap: var(--spacing-sm);
  }
  
  .role-status {
    flex-direction: row;
    align-items: center;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
}
</style>